'use strict';

const Controller = require('egg').Controller;
class MoviesController extends Controller {
  async find(m) {
    const db = this.app.mongodb;
    const res = await db.collection(m).find().toArray();
    return res;
  }
  async getMovieDetailOrSearch(obj) {
    const db = this.app.mongodb;
    const tables = [ 'top250', 'inTheaters', 'comingSoon' ];
    const sum = [];
    for (let i = 0; i < tables.length; i++) {
      if(obj.id && obj.collected == 'undifined'){
        var {id} = obj;
        const res = await db.collection(tables[i]).find({ _id: id }).toArray();
        sum.push(...res);
      }else if(obj.keyword){
        var {keyword} = obj;
        keyword = new RegExp(keyword);    
        //没有办法直接查，需要正则查询
        //find({title:/你/})
        const res = await db.collection(tables[i]).find({ title: keyword }).toArray();
        sum.push(...res);
      }else if(obj.id && obj.collected != 'undifined'){
        var {id,collected} = obj;
        await db.collection(tables[i]).updateOne({_id:id},{$set:{collected:collected}});
        const res = await db.collection(tables[i]).find({ _id: id }).toArray();
        sum.push(...res);
      }
    }
    return sum;
  }
}

module.exports = MoviesController;
